"""
属于当前子应用的公共函数或类库方法
"""
import re


from django.contrib.auth.backends import ModelBackend


from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功的返回数据
    :param token: 生成token的对象
    :param user: 当前已经登录的用户【在登录视图/注册视图】
    :param request: 本次的请求对象
    :return:
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


def get_user_by_account(account):
    """
    根据账号信息获取用户
    :param account: 账号
    :return:
    """
    try:
        if re.match('^1[3-9]\d{9}$', account):
            user = User.objects.filter(mobile=account).get()
        else:
            user = User.objects.filter(mobile=account).get()
    except User.DoesNotExist:
        # 找不到对应的用户
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        根据用户提供的信息，返回登录用户，自定义用户认证
        :param request: 本次请求对象
        :param username: 用户名或者手机号【并不一定是用户的名字，还有你要实现的其他可登录信息】
        :param password: 登录密码
        :param kwargs:
        :return:
        """
        user = get_user_by_account(username)
        if user is not None and user.check_password(password):
            return user


from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadData
from django.conf import settings
from . import constants


def generate_save_user_token_url(user):
    """
    使用itsdangerous保存openid，生成access_token
    :param user:
    :return:
    """
    serializer = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    # serializer.dumps(数据), 返回bytes类型
    data = {'user.id': user.id}
    token = serializer.dumps(data)
    token = token.decode()
    # 拼装url地址
    verify_url = settings.VERIFY_EMAIL_HTML + '?token=' + str(token)

    return verify_url


def check_verify_email_token(token):
    serializer = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = serializer.loads(token)
        return data['user_id']
    except BadData:
        return None
